package com.tstudy.laoshibang.share;

import java.io.ByteArrayOutputStream;

import org.apache.http.Header;
import org.json.JSONObject;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXVideoObject;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.login.ThirdLoginCallBack;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.utils.SharedPreferencesUtil;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

public class WrapWechat {
	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
	private IWXAPI mApi;
	Activity mActivity;

	private WrapWechat() {

	}

	private static WrapWechat instance = new WrapWechat();

	public static WrapWechat getInstance() {
		return instance;
	}

	ShareResultListener mShareResultListener;

	/**
	 * 注册应用至微信
	 * 
	 * @param activity
	 */
	public void registAppId(Activity activity) {
		mActivity = activity;
		mApi = WXAPIFactory.createWXAPI(BaseApplication.mContext, CONSTANT.WECHAT_APP_ID, true);
		mApi.registerApp(CONSTANT.WECHAT_APP_ID);
		mApi.handleIntent(activity.getIntent(), (IWXAPIEventHandler) activity);
	}
	
	public void auth(){
		final SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";
		req.state = "none";
		mApi.sendReq(req);
		LogUtil.d("--execute wechat login" );
	}

	static ThirdLoginCallBack mCallback;
	public void login(ThirdLoginCallBack callback) {
		mCallback = callback;
		String refreshToken = SharedPreferencesUtil.getWechatAuthInfo(CONSTANT.OAUTH.REFRESH_TOKEN);
//		if (TextUtils.isEmpty(refreshToken)) {
			auth();
//		}else{
//			long bindTime = Long.valueOf(SharedPreferencesUtil.getWechatAuthInfo(CONSTANT.OAUTH.BIND_TIME));
//			if (isTokenExpried(bindTime)) {
//				refreshToken(refreshToken);
//			}else{
//				String wechatUserInfo = SharedPreferencesUtil.getWechatUserInfo();
//				if (!TextUtils.isEmpty(wechatUserInfo)) {
//					try {
//						JSONObject response = new JSONObject(wechatUserInfo);
//						if (mCallback != null) {
//							mCallback.onAuthComplete(true);
//							String openId= response.optString("openid");
//							String unionId= response.optString("unionid");
//							String nickName= response.optString("nickname");
//							int sexInt= response.optInt("sex");
//							String headImgUrl= response.optString("headimgurl");
////							int sexInt = "m".equals(sex) ?CONSTANT.SEX_MALE:CONSTANT.SEX_FEMALE;
//							mCallback.onSuccess(CONSTANT.USER_SOURCE_WECHAT, openId, nickName, sexInt, headImgUrl);
////							LoginManager.getInstance().loginByWechat(openId, unionId, nickName, sex, headImgUrl, mCallback);
//						}
//					} catch (JSONException e) {
//						e.printStackTrace();
//					}
//				}else{
//					auth();
//				}
//			}
//		}
	}
	/**
	 *获取微信的 accesstoken
	 * @param code
	 * {"openid":"ol-_ZsgLTqAQz5OEOzZmQr0-dl5Q","expires_in":7200,"scope":"snsapi_userinfo","refresh_token":"OezXcEiiBSKSxW0eoylIeLQEkUDBsygV1zr5MPzShWw7NKNr3OdGZ-fQ8K7UhMuvr1DNofZ-N_tDFs5bsxomLpnyNAJg68UHSgryY8lvf-FNrTeVP3sm2bU8QrV0zuVVXmnHEviq1-H0hlYzAvBJKQ","access_token":"OezXcEiiBSKSxW0eoylIeLQEkUDBsygV1zr5MPzShWw7NKNr3OdGZ-fQ8K7UhMuvu-SAcmdgt-dgQZ25boSdkNn273_aPKdbDOQoIo0GiYpzZA_erR3QYM-zVEoNSDLEdPe0HqQmFrTLPin3BsIP1g","unionid":"oLnqfsyAtJkHTAZ6rmvLHcldaL54"}
	 */
	public void getAccessToken(String code) {
		JsonHttpResponseHandler response = new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
				LogUtil.d("---wechat auth response==" + response);
//				{"errmsg":"missing code","errcode":41008}
				if (response != null && !TextUtils.isEmpty(response.optString(CONSTANT.OAUTH.ACCESS_TOKEN))) {
					if (mCallback != null) {
						mCallback.onAuthComplete(true);
					}
					String accessToken = response.optString(CONSTANT.OAUTH.ACCESS_TOKEN);
					String openId = response.optString(CONSTANT.OAUTH.OPEN_ID);
					String expiresIn = response.optString(CONSTANT.OAUTH.EXPIRES_IN);
					String refreshToken = response.optString(CONSTANT.OAUTH.REFRESH_TOKEN);
					SharedPreferencesUtil.saveWechatAuthInfo(accessToken, openId, expiresIn, refreshToken);
					getUserInfo(accessToken, openId);
				}else{
					BaseApplication.showToast("微信授权失败");
				}
			};
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
			}
			@Override
			protected void handleMessage(Message message) {
				// TODO Auto-generated method stub
				super.handleMessage(message);
			}
		};
		
		HttpManager.getInstance().getWechatAccessToken(code, response);
	}
	
	public void refreshToken(String refreshToken) {
		JsonHttpResponseHandler response = new JsonHttpResponseHandler() {
			public void onSuccess(JSONObject response) {
				if (response != null) {
					if (mCallback != null) {
						mCallback.onAuthComplete(true);
					}
					String accessToken = response.optString(CONSTANT.OAUTH.ACCESS_TOKEN);
					String openId = response.optString(CONSTANT.OAUTH.OPEN_ID);
					String expiresIn = response.optString(CONSTANT.OAUTH.EXPIRES_IN);
					String refreshToken = response.optString(CONSTANT.OAUTH.REFRESH_TOKEN);
					SharedPreferencesUtil.saveWechatAuthInfo(accessToken, openId, expiresIn, refreshToken);
					getUserInfo(accessToken, openId);
				}else{
					BaseApplication.showToast("获取微信token失败");
				}
			};
		};
//		HttpManager.getInstance().refreshWechatToken(refreshToken, response);
	}
	
	/*
	 * 一审中延迟
	 */
	public boolean isTokenExpried(long bindTime){
		return bindTime - 60*1000 < System.currentTimeMillis();
	}

	/**
	 * 获取微信用户信息
	 * @param accessToken
	 * @param openId
	 */
	public void getUserInfo(String accessToken, String openId) {
		JsonHttpResponseHandler response = new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
				if (response != null) {
					if (mCallback != null) {
						String openId= response.optString("openid");
						String unionId= response.optString("unionid");
						String nickName= response.optString("nickname");
						int sexInt= response.optInt("sex");
						String headImgUrl= response.optString("headimgurl");
						SharedPreferencesUtil.saveWechatUseInfo(response.toString());
//						LoginManager.getInstance().loginByWechat(openId, unionId, nickName, sex, headImgUrl, mCallback);
						mCallback.onSuccess(CONSTANT.USER_SOURCE_WECHAT, openId, nickName, sexInt, headImgUrl);
					}
				}
			};
		};
		HttpManager.getInstance().getWXUserInfo(accessToken, openId,response);

	}

	/**
	 * 检查微信版本，确定是否发送至朋友圈
	 * 
	 * @return
	 */
	public boolean checkVersion() {
		int wxSdkVersion = mApi.getWXAppSupportAPI();
		if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
			return true;
		} else {
			return false;
		}
	}
	
	public boolean isInstall(){
		return mApi.isWXAppInstalled();
	}

	/**
	 * 分享图片至微信，可以为url或二进制数据
	 * 
	 * @param url
	 * @param mImageFetcher
	 */
	public void shareImageToWechat(final String title,final String description,String filePath, String url,final Boolean isTimeline) {
		LogUtil.e("sharetowechat", "--sharetowechat image url==" + url);
		Bitmap bmp = null;
		if (TextUtils.isEmpty(filePath)) {//
			ImageLoader.getInstance().loadImage(url,
					new ImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							shareBitmapToWechat(title,description,loadedImage, isTimeline);
						}

						@Override
						public void onLoadingCancelled(String imageUri,
								View view) {
						}
					});
		} else {
			bmp = BitmapFactory.decodeFile(filePath);
			shareBitmapToWechat(title,description,bmp, isTimeline);
		}
	}

	public void shareBitmapToWechat(String title,String description,Bitmap bmp, boolean isTimeline) {
		boolean result = false;
		try {
			WXImageObject imgObj = new WXImageObject(bmp);
			WXMediaMessage msg = new WXMediaMessage();
			msg.mediaObject = imgObj;
			Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 110, 110, true);
			msg.thumbData = bmpToByteArray(thumbBmp, true);

			LogUtil.d("sendToWechat", "--msg.thumbData  "
					+ msg.thumbData.length);
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("img");
			req.message = msg;
			msg.title = title;
			msg.description = description;
			req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline
					: SendMessageToWX.Req.WXSceneSession;
			result = mApi.sendReq(req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result) {
			if (mShareResultListener != null) {
				mShareResultListener.onSuccess(1, "wechat", "true");
			}
		} else {
			if (mShareResultListener != null) {
				mShareResultListener.onError(1, "wechat", "false");
			}
		}
	}

	/**
	 * 分享视频到微信
	 * 
	 * @param url
	 */
	public void shareVideoToWechat(String url, boolean isTimeline) {
		WXVideoObject video = new WXVideoObject();
		// 根据url分享
		video.videoLowBandUrl = url;
		WXMediaMessage msg = new WXMediaMessage(video);
		msg.title = "Video Title";
		msg.description = "Video Description";
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("video");
		req.message = msg;
		req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline
				: SendMessageToWX.Req.WXSceneSession;
		boolean result = mApi.sendReq(req);
		if (result) {
			if (mShareResultListener != null) {
				mShareResultListener.onSuccess(1, "wechat", "true");
			}
		} else {
			if (mShareResultListener != null) {
				mShareResultListener.onError(1, "wechat", "false");
			}
		}

	}

	/**
	 * 分享链接到微信
	 * 
	 * @param url
	 * @param thumb
	 * @param isTimeline
	 *            是否分享到朋友圈
	 */
	public void shareWebPageToWechat(String title, String description,String url, Bitmap thumb,boolean isTimeline) {
		LogUtil.d("wechat share url ::" + url + ",title==" + title);
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = url;
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = title;
		msg.description = description;
		Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb, 110, 110, true);
		msg.thumbData = bmpToByteArray(thumbBmp, true);
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline: SendMessageToWX.Req.WXSceneSession;
		boolean result = mApi.sendReq(req);
		if (result) {
			if (mShareResultListener != null) {
				mShareResultListener.onSuccess(1, "wechat", "true");
			}
		} else {
			if (mShareResultListener != null) {
				mShareResultListener.onError(1, "wechat", "false");
			}
		}
		LogUtil.d("wechat share finish");
	}

	public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	public interface ShareResultListener {
		public void onSuccess(int type, String typeStr, String success);

		public void onError(int type, String typeStr, String errorMsg);
	}

	public ShareResultListener getShareResultListener() {
		return mShareResultListener;
	}

	public void setShareResultListener(ShareResultListener mShareResultListener) {
		this.mShareResultListener = mShareResultListener;
	}

}
